var wechat = require('wechat');
var request = require('request');
var menuController = require('./MenuController');
var noticeController = require('./NoticeController');
require('date-util');
var config = require('../../config');
var moment = require('moment');
var dao=require('../../common/utils/appUtils');
var redistool=require('../../common/utils/redistools');
var oauthDao = require('../dao/OauthDao');
var redbag = require('../models/RedBag');
var redq = require('../models/Pipe');
var async = require('async');
var model=require('../models/ScanStatusModel');
var spreaderModel = require('../models/SpreaderModel');


module.exports.reply = wechat(config.app, wechat.text(function (message, req, res) {
    // console.log(message);
    var input = (message.Content || '').trim();
    var from = (message.FromUserName || '').trim();

    if (input === 'notice') {
        noticeController.queryNotice(function (notices) {
            var noticeStr = '';
            for (var i = 0; i < notices.length; i++) {
                noticeStr += '公告' + (i + 1) + ': ' + notices[i] + '\n\n';
            }
            res.reply(noticeStr);
        }, req)
        return;
    }

    if (input == '抢红包') {

        var date = moment().format("MMDD").toString();
        // 检查是否存在用户

        redbag.validUser(from, function (reslut) {

            // redistool.lock('redbag',function (result) {

                redq.enQueue({isSuccess:res.isSuccess,key:from,callback:function (result) {
                    res.reply(result.message);
                }})
            // })


            // if (!reslut.isSuccess) {
            //     res.reply('<a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxaf378ab4ba9fb3da&redirect_uri=http%3A%2F%2F1a65369r25.iask.in%2Fmemberhome&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect">您尚未注册，请点击注册再抢红包！</a> ');
            //     // res.reply('<a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb8559b450f58c079&redirect_uri=http%3A%2F%2F1a65369r25.iask.in%2Fmemberhome&response_type=code&scope=snsapi_base&state=123#wechat_redirect">您尚未注册，请点击注册再抢红包！</a> ');
            // } else {
            //     //进行抢红包
            //     //redis 缓存,抢红包次数是否超过3次。key：当前日期+openid+(红包id)  过期时间：24小时
            //     // redbag.getRedBag(from, function (reslut) {
            //     //     res.reply(reslut);
            //     // })
            //
            //     redq.enQueue({key:from,callback:function (result) {
            //         // var i=0;
            //
            //         res.reply(result.message);
            //     }})
            // }

        })
        return;
    }

    if(input == '推广统计'){
        let url = '<a  href="'+config.domain+'spreaderview">点击查看推广统计</a> ';
        res.reply(url);
        return;
    }

    if (input == 'menu') {
        if (from === 'oSx2ps3VEXZVlbPVhtvOiNaW_gm0') {
            menuController.customMenu(function () {
                res.reply('已更新自定义菜单，如果没有看到变化，请等待5分钟，等待5分钟还无变化，说明你的菜单是最新的');
            });
        } else if (from === 'oIPTPwXrH4oFXFwTE2zj5VjV7TFY') {
            console.log('master--微信自定义菜单更新');
            menuController.customMenu(function () {
                res.reply('已更新自定义菜单，如果没有看到变化，请等待5分钟，等待5分钟还无变化，说明你的菜单是最新的');
            });
        } else if (from === 'oSx2pszAztjzEwHKfr7yWhdg2Bz4') {
            menuController.customMenu(function () {
                res.reply('已更新自定义菜单，如果没有看到变化，请等待5分钟，等待5分钟还无变化，说明你的菜单是最新的');
            });
        } else {
            console.log('master--没进入菜单更新');
            content = 'who are you?';
        }
        return;
    }

    if (input === 'login') {
        res.reply([{
            title: '登陆页面',
            description: '去登陆',
            picurl: 'test.jpg',
            url: '/loin'
        }]);
        return;
    }

    // if (input === '天气') {
    //     res.wait('weather');
    // }

    if (input === 'now') {
        return res.reply('现在时间是：' + new Date().format('yyyy-mm-dd HH:MM:ss'));
    }
    if (input.length < 2) {
        return res.reply('内容太少，请多输入一点:)');
    }

    if (input === 'hello') {
        var from = message.FromUserName;
        var content = '';
        if (from === 'oSx2ps3VEXZVlbPVhtvOiNaW_gm0') {
            content = 'hello master';
        } else if (from === 'oIPTPwXrH4oFXFwTE2zj5VjV7TFY') {
            content = 'hello manager';
        } else {
            content = 'who are you?'
        }
        //console.log(content);
        res.reply(content);
        return;
    }



    if(input=='申请推广'){
        async.waterfall([
            function (callback) {
                dao.baseDao('','select access_token from gdas_wechat_access_token where id=1',null,function (result) {
                    callback(null,result.rows[0].access_token)
                })
            },
            function (arg,callback) {
                dao.baseDao('','select member_id from member_user where openid=?',from,function (reslut) {
                    if(!reslut.isSuccess||reslut.rows.length<1) {
                        callback('您尚未注册会员，无法获得推广链接，请先注册')
                    }else{
                        callback(null, arg, reslut.rows[0].member_id);
                    }
                })
            },
            function (arg, arg1,callback) {
                var url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='+arg ;
                request({
                    url: url,
                    method: "POST",
                    json: true,
                    headers: {
                        "content-type": "application/json",
                    },
                    body: {"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": arg1}}}
                }, function(error, response, body) {
                    // console.log(JSON.stringify(response));
                    callback(null,body.ticket,arg,arg1);

                });
            },function (arg,token,arg1, callback) { //查看是否存在标签
                //查找标签
                var url = 'https://api.weixin.qq.com/cgi-bin/tags/get?access_token=' + token;

                request({
                    url: url,
                    method: "POST",
                    json: true,
                    headers: {
                        "content-type": "application/json",
                    },
                    body: {
                    }
                }, function (error, response, body) {
                    // console.log(JSON.stringify(response));

                    if (body.hasOwnProperty('tags') && body.tags.length > 0) {
                        var has=false;
                        for (var i = 0; i < body.tags.length; i++) {
                            if (body.tags[i].name === '推广链接'+arg1) {
                                has=true;
                                tagid = body.tags[i].id;
                                // callback(null, tagid)
                            } else {

                            }
                        }
                        // 没有标签，新建标签
                        if (!has) {
                            var url = 'https://api.weixin.qq.com/cgi-bin/tags/create?access_token='+token ;
                            request({
                                url: url,
                                method: "POST",
                                json: true,
                                headers: {
                                    "content-type": "application/json",
                                },
                                body: {  "tag" : {
                                    "name" : '推广链接'+arg1//标签名
                                }}
                            }, function(error, response, body) {
                                // console.log(JSON.stringify(response));
                                // callback(null,arg)
                            });
                        }else{
                            // callback(null,arg)
                        }
                    }
                }.bind(arg1));

                callback(null,arg);


            }
        ],function (err, result){
            if(err) {
                res.reply(err);
                return;
            }else if(result) {
                let url = '<a  href="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='+result+'">点击获取二维码</a> ';
                let url2 = '<a  href="'+config.domain+'spreader?open_id='+from+'">点击查看您的推广情况</a> ';
                let params = {
                    openid:from,
                    qrcodeaddress:url
                }
                spreaderModel.saveSpreader(params);
                //添加标签
                let  content = '* * * * * * * * * * * * * *'+ '\n\n';
                content += '  二维码链接：\n  '+url+'\n\n';
                content += '  查看个人推广链接:\n  '+ url2+'\n\n';
                content += '* * * * * * * * * * * * * *';
                res.reply(content);
                return;
            }
        })
    }else{
        res.reply('');
    }
}).image(function (message, req, res) {
    //console.log(message);
    res.reply('pic');
}).location(function (message, req, res) {
    //console.log(message);
    res.reply('location');
}).voice(function (message, req, res) {
    //console.log(message);
    res.reply('voice');
}).link(function (message, req, res) {
    //console.log(message);
    res.reply('link');
}).event(function (message, req, res) {
    if (message.Event === 'subscribe') {
        // 用户添加时候的消息
        res.reply('欢迎关注公众号');
    } else if (message.Event === 'unsubscribe') {
        res.reply('Bye!');
    } else if (message.Event === 'CLICK') {
        var eventKey = message.EventKey;
        switch (eventKey) {
            case 'notice' : {
                noticeController.queryNotice(function (notices) {
                    var noticeStr = '';
                    for (var i = 0; i < notices.length; i++) {
                        noticeStr += '公告' + (i + 1) + ': ' + notices[i] + '\n\n';
                    }
                    res.reply(noticeStr);
                }, req);
                break;
            }
            case 'praise' : {
                res.reply('谢谢您的支持!');
                break;
            }
        }
    } else if (message.Event === 'LOCATION') {
        res.reply('');
    }else if(message.Event==='SCAN'){
        var from = (message.FromUserName || '').trim();
        model.scan([from,message.EventKey],function () {

        });
        let params={
            open_id :from,
            member_id:parseInt(message.EventKey)
        }
        spreaderModel.saveScanOpenid(params,function (err,result) {
            console.log(result.message);
        });
        res.reply('');
        return;


    }

    else {
        //res.reply('暂未支持! Coming soon!');
        res.reply('');
    }
}));